package com.example.it.looker.model.datasource;

import com.example.it.looker.Global;
import com.example.it.looker.model.entity.Image;
import com.example.it.looker.utils.L;
import com.example.it.looker.utils.NetUtil;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by 鲁迅认识的那只猹 on 9/5/2017 3:57 PM.
 * Emial 1258730808@qq.com
 * Desc:
 */

public class ImageDataSource {

    private int pageIndex = 0;

    private static ImageDataSource IMAGE_DATA_SOURCE;

    private ImageDataSource() {

    }

    public static ImageDataSource getInstance() {
        if (IMAGE_DATA_SOURCE == null)
            IMAGE_DATA_SOURCE = new ImageDataSource();
        return IMAGE_DATA_SOURCE;
    }

    /**
     * 加载数据，加载更多同样调用此方法
     */
    public List<Image> load() {
        List<String> urlList = new ArrayList<String>();
        for (int i = pageIndex; i < pageIndex + Global.COUNT_EACH; i++) {
            urlList.add(Global.getBingImage(pageIndex));
            pageIndex++;
        }
        List<Image> imageList = new ArrayList<>();
        for (int i = 0; i < urlList.size(); i++) {
            imageList.add(toImage(urlList.get(i)));
        }
        return imageList;
    }

    /**
     * 获取JSON数据，转换为Image对象
     */
    private Image toImage(String url) {
        String jsonContent = NetUtil.getRequest(url);
        try {
            JSONObject jsonObject = new JSONObject(jsonContent).getJSONArray("images").getJSONObject(0);
            String imgUrl = jsonObject.getString("url");
            String copyright = jsonObject.getString("copyright");
            String enddate = jsonObject.getString("enddate");

            Image image = new Image(copyright, Global.getBingImage(imgUrl), enddate);
            return image;
        } catch (Exception e) {
            e.printStackTrace();
            L.i("ImageDataSource.toImage Error");
            return null;
        }
    }

}
